package com.omesoft.hksnore.monitoring;

import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.omesoft.hksnore.MainActivity;
import com.omesoft.hksnore.R;
import com.omesoft.hksnore.util.L;
import com.omesoft.hksnore.util.ble.BluetoothLeService;
import com.omesoft.hksnore.util.ble.SampleGattAttributes;
import com.omesoft.hksnore.util.constant.CusConstant;
import com.omesoft.hksnore.util.dao.MendaleSleepAllIfc;
import com.omesoft.hksnore.util.dao.MendaleSleepAllIfcImpl;
import com.omesoft.hksnore.util.dao.MendaleSleepIfc;
import com.omesoft.hksnore.util.dao.MendaleSleepIfcImpl;
import com.omesoft.hksnore.util.data.MyDateUtil;
import com.omesoft.hksnore.util.data.MySharedPreferencesUtil;
import com.omesoft.hksnore.util.dialog.MyProgressBarDialogUtil;
import com.omesoft.hksnore.util.entity.Medix_Pub_Sync_Sleep;
import com.omesoft.hksnore.util.entity.Medix_Pub_Sync_SleepDetail;
import com.omesoft.hksnore.util.file.CreateFiles;
import com.omesoft.hksnore.util.json.SyncUtil;
import com.omesoft.hksnore.util.myactivity.BaseFragment;
import com.omesoft.hksnore.util.newsnore.SnoreRecordThread;
import com.omesoft.hksnore.util.omeview.MyDialog;
import com.omesoft.hksnore.util.omeview.NumberSeekBar2;
import com.omesoft.hksnore.util.omeview.RecordPragram;
import com.omesoft.hksnore.util.omeview.WheelUtil;
import com.omesoft.hksnore.util.photo.SettingUtil;
import com.omesoft.hksnore.util.snore.SnoreMonitor;
import com.omesoft.hksnore.util.titlebar.MyTitlebarUtil;

import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 监测界面
 *
 * @autor omesoft_lgc
 * <p/>
 * create at 2017/2/16 15:29
 */
public class MonitorFragment extends BaseFragment implements OnClickListener, View.OnLongClickListener, SeekBar.OnSeekBarChangeListener {
    private String TAG = "MonitorFragment";

    private Canvas canvas1 = null;
    private boolean isFirstDraw = true;
    /**
     * 已经显示的数据波形 最多能够显示的单位格数量(横坐标 15px 为一个单位格)
     */
    private int maxNum = 0;
    /**
     * 在画布上正在显示的数据集合
     */
    private ArrayList<Float> showedList0 = new ArrayList<Float>();
    private ArrayList<Float> showedList1 = new ArrayList<Float>();
    private ArrayList<Float> showedList01 = new ArrayList<Float>();
    private ArrayList<Float> showedList11 = new ArrayList<Float>();

    public boolean isOpenHis = false;
    // public String fileName = "";
    // public String newfileName = "";
    private Dialog confirmDialog;
    private Dialog openBluetoothDialog;
    private Dialog bltConnectAgain;



    private int bluetoothConnectTag = 0;//蓝牙连接标记时间


    private View mainView;
    private Context context;
    private Activity activity;
    private TimerTask task;
    private Timer timer;
    private Button mStatr_btn;//mTest_btn, mConnect_btn
    private TextView mConnectText_tv;

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeService mBluetoothLeService;
    public BluetoothAdapter mBTAdapter = null;
    private boolean isDisBle = false;
    private int vbType = 0;// 震动类型

    //    private TextView mSnoreCount_tv, mSnoreTimeHour_tv, mSnoreTImeMin_tv, mSnoreStopCount_tv,
//            mBreathing_tv, mMove_tv, mTurnMova_tv, mNoData_tv;
    private TextView mTestTime;

    private boolean isFinish1 = true;
    private boolean isExit = false; // 是否退出
    private boolean isStart = true;
    private boolean isSetMaxNum = false;
    public static boolean isMonitor = false;
    private boolean isFrist = true;//判断是否第一次进入
    private boolean isFrist2 = true;//判断是否第一次进入
    private MendaleSleepIfc mifc;
    private MendaleSleepAllIfc allIfc;
    private Medix_Pub_Sync_Sleep dto;
    private Medix_Pub_Sync_SleepDetail detailDTO;
    private long vbTime = 0;
    private long waiteTime = 2000;
    private long addTime = 5000;
    private long monitorActionTime = 0;
    /*  同步数据*/
    private String Sleep_Id = "";
    private String Inbed_Tmie = "";
    private String Sleep_Time = "";
    private String Remark = "";
    private int Snore_conut = 0;
    private int Snore_Stop_count = 0;
    private int Snore_Duration = 0;//鼾声持续时间
    private int Act_Count = 0;
    private int Turn_Count = 0;
    private int Breath_Rate = 0;

    private int Snore_conut_d = 0;
    private int Snore_Stop_count_d = 0;
    private int Snore_Duration_d = 0;//鼾声持续时间
    private int Act_Count_d = 0;
    private int Turn_Count_d = 0;
    private int Breath_Rate_d = 0;


    private String StartData = "";//监测开始时间
    private String initCount = "";
    private int detialRemark = 0;//SleepDetialId自增参数
    private NumberSeekBar2 mSnoreStopLV_seek;
    private ImageButton mSnoreStopMode_img;
    private TextView mSnoreStopLV_tv, mInSleepTime_tv;
    private LinearLayout mSnoreStopLV_ll, mInSleepTime_ll,mMonitorBG_ll;


    private RecordPragram monitor_recordpragram;
    public static boolean isMonitorEnd = false;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
        context = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.snore_fragment_monitor, container, false);

        return mainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initFile();
        initView();
        initHandler();
        initTitle();

    }


    private void initTitle() {
        MyTitlebarUtil.setStateHeight(getActivity(), mainView.findViewById(R.id.state_bar), R.string.snore_main_monitor, mainView);


    }

    private void initFile() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        CreateFiles.createFileDirs();
    }

    protected void initView() {
        mifc = new MendaleSleepIfcImpl(context);
        allIfc = new MendaleSleepAllIfcImpl(context);
        dto = new Medix_Pub_Sync_Sleep();
        detailDTO = new Medix_Pub_Sync_SleepDetail();
        mStatr_btn = (Button) mainView.findViewById(R.id.monitor_start_btn);
        mStatr_btn.setOnClickListener(this);
        mStatr_btn.setOnLongClickListener(this);
        mConnectText_tv = (TextView) mainView.findViewById(R.id.monitor_connect_state);
        mSnoreStopMode_img = (ImageButton) mainView.findViewById(R.id.monitor_shack_switch_ib);
        mSnoreStopMode_img.setOnClickListener(this);
        mSnoreStopLV_ll = (LinearLayout) mainView.findViewById(R.id.moniter_set_snore_stop_lv_ll);
        mSnoreStopLV_ll.setOnClickListener(this);
        mInSleepTime_ll = (LinearLayout) mainView.findViewById(R.id.moniter_set_in_sleep_time_ll);
        mInSleepTime_ll.setOnClickListener(this);
        mSnoreStopLV_tv = (TextView) mainView.findViewById(R.id.moniter_snore_lv_tv);
        mInSleepTime_tv = (TextView) mainView.findViewById(R.id.moniter_in_sleep_tv);
        mMonitorBG_ll = (LinearLayout) mainView.findViewById(R.id.moniter_bg);
        mSnoreStopLV_tv.setText(MySharedPreferencesUtil.getMaxVbLv(context) + "");
        mInSleepTime_tv.setText(MySharedPreferencesUtil.getInSleepTime(context) + "");
        //设置字体
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/ROBOTO-THIN.TTF");
        mSnoreStopLV_tv.setTypeface(typeface);
        mInSleepTime_tv.setTypeface(typeface);
//        mSnoreTimeHour_tv = (TextView) mainView.findViewById(R.id.monitor_sonre_time_hour);
//        mSnoreTImeMin_tv = (TextView) mainView.findViewById(R.id.monitor_sonre_time_min);
//        mSnoreCount_tv = (TextView) mainView.findViewById(R.id.monitor_sonre_count);
//        mSnoreStopCount_tv = (TextView) mainView.findViewById(R.id.monitor_sonre_stop);
//        mBreathing_tv = (TextView) mainView.findViewById(R.id.monitor_sonre_breath);
//        mMove_tv = (TextView) mainView.findViewById(R.id.monitor_sonre_move);
//        mTurnMova_tv = (TextView) mainView.findViewById(R.id.monitor_sonre_turn_mova);
//        mNoData_tv = (TextView) mainView.findViewById(R.id.monitor_no_date);
        mTestTime = (TextView) mainView.findViewById(R.id.moniter_test_time);
        mTestTime.setTypeface(typeface);
        monitor_recordpragram = (RecordPragram) mainView.findViewById(R.id.monitor_recordpragram);

    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        isFinish1 = true;
        if (SettingUtil.isOpenBle2 && isOpenHis) {
            isOpenHis = false;
            setBtnText();
        }
        if (MySharedPreferencesUtil.getSwitch(context) == true) {
            SnoreStopModeON();
            mSnoreStopMode_img.setBackground(getResources().getDrawable(R.drawable.device_shack_switch_btn));

        } else {
            stopTime();
            stopService();
            StopSnoreModeOFF();
            mSnoreStopMode_img.setBackground(getResources().getDrawable(R.drawable.device_shack_switch_btn_off));

        }

    }


    protected void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        showedList0 = (ArrayList<Float>) msg.obj;
                        break;
                    case 1:
                        showedList01 = (ArrayList<Float>) msg.obj;
                        break;
                    case 2:
                        showedList01 = (ArrayList<Float>) msg.obj;
                        break;
                    case CusConstant.DRAW_LINE://画图
                        showedList1 = (ArrayList<Float>) msg.obj;

                        break;
                    case CusConstant.SNORE_COUNT://打鼾次数
                        if (isFinish1) {
                            Snore_conut = Integer.parseInt(msg.obj.toString());
//                            mSnoreCount_tv.setText(Snore_conut + "");
                            Log.e("xxxx", "  Snore_conut。。。。。。" + Snore_conut);
                        }

                        break;
                    case CusConstant.SNORE_TIME://打鼾时长
                        if (isFinish1) {
                            Snore_Duration = Math.round(Float.parseFloat(msg.obj.toString()));
                            Log.e("xxxx", "  SNORE_TIME。。。。。。" + Snore_Duration);
                        }

                        break;

                    case CusConstant.TEST_TIME://测试时间
                        if (isFinish1) {
                            mTestTime.setText(msg.obj.toString());
                        }
                        break;
                    case CusConstant.BREATH_RATE://呼吸频率
                        if (isFinish1) {
                            Breath_Rate = Integer.parseInt(msg.obj.toString());
//                            mBreathing_tv.setText(Breath_Rate + "");
                        }

                        break;
                    case CusConstant.ACT_COUNT://体动
                        if (isFinish1) {
                            Act_Count = Integer.parseInt(msg.obj.toString());
//                            mMove_tv.setText(Act_Count + "");
                        }
                        break;
                    case CusConstant.TRUN_COUNT://翻身
                        if (isFinish1) {
                            Turn_Count = Integer.parseInt(msg.obj.toString());
//                            mTurnMova_tv.setText(Turn_Count + "");
                        }
                        break;
                    case 18:
                        showedList11 = (ArrayList<Float>) msg.obj;
                        if (isFinish1) {
                        }
                        break;


                    case CusConstant.SNORE_STOP_COUNT://止鼾次数

                        if (MySharedPreferencesUtil.getSwitch(context)) {
                            Snore_Stop_count = Integer.parseInt(msg.obj.toString());
//                            mSnoreStopCount_tv.setText(Snore_Stop_count + "");

                        }
                        break;
                    case 21://关闭震动
                        Log.e("xx", "  震动停止。。。。。。");
                        if (MySharedPreferencesUtil.getSwitch(context)) {
                            if (vbType == 1) {
                                if (mBluetoothLeService != null) {
                                    vbType = 0;
                                    SampleGattAttributes.vbControl(mBluetoothLeService, vbType);
                                }
                            }
                        }
                        break;
                    case CusConstant.SNORE_STOP://开启震动
                        Log.e("xx", "  震动开始。。。。。。");
                        int level = (Integer) msg.obj;
                        Log.e("xx", "  震动强度。。。。。。" + level);
                        if (MySharedPreferencesUtil.getSwitch(context)) {
                            VBLV(level);

                        }
                        break;
                    case SettingUtil.BLE_DIS://断开蓝牙
                        if (vbType == 1) {
                            if (mBluetoothLeService != null) {
                                vbType = 0;
                                SampleGattAttributes.vbControl(mBluetoothLeService,
                                        vbType);
                            }
                        }

                        break;

                    case CusConstant.SYNC_DETIAL:
                        SyncDetial();
                        break;
                    case CusConstant.SYNC_ALL:
                        Syn();
                        break;

                    case 1000001:
                        L.e("sherlock", "蓝牙连接状态10000001    " + BluetoothLeService.BTState);


                        switch (BluetoothLeService.BTState) {
                            case 1://断开
                                waitingBltConnect();
                                if (MySharedPreferencesUtil.getSwitch(context)) {
                                    SnoreStopModeON();
                                }
                                break;
                            case 2://连接
                                if (bltConnectAgain != null && bltConnectAgain.isShowing()) {
                                    bltConnectAgain.dismiss();
                                }
                                connectButtonText();
                                if (!isMonitor) {//监测未开始时开启监测
                                    startRecordNew();
                                }
                                break;
                            case 3://搜索
                                waitingBltConnect();
                                waitingConnectButtonText();
                                break;
                            case 4://设备不支持蓝牙4.0

                                break;
                            case SettingUtil.BLE_DIS://断开蓝牙
                                waitingBltConnect();
                                SnoreStopModeON();
                                break;

                        }
                        break;
                    default:
                        break;
                }
            }
        };

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.monitor_start_btn://开始按钮
                if (isStart) {
                    isFinish1 = true;
                    StartData = MyDateUtil.getStartOrEndTime();//保存监测开始时间
                    if (MySharedPreferencesUtil.getSwitch(context)) {//是否开启了止鼾模式
                        if (mBTAdapter == null || mBluetoothLeService == null) {//蓝牙未连接则询问是否连接蓝牙
                            bluetoothAskDialog();
                        } else {//已连接则开始止鼾监测
                            bluetoothConnect();
                        }
                        return;
                    } else {
                        startRecordNew();
                        StopSnoreModeOFF();
                    }
                } else {

                }

                break;

            case R.id.monitor_shack_switch_ib://止鼾模式开关
                SnoreSotopModeSwitch();
                break;
            case R.id.moniter_set_snore_stop_lv_ll://止鼾等级layout
                ArrayList<String> mList = new ArrayList<>();
                for (int i = 1; i < 10; i++) {
                    mList.add(i + " 级止鼾");
                }
                if (vbType == 1 && BluetoothLeService.BTState == 2) {//打开选择止鼾等级时，如果正在震动先停止震动
                    vbType = 0;
                    SampleGattAttributes.vbControl(mBluetoothLeService, vbType);
                }
                WheelUtil.alertBottomWheelOption(context, mList, 1, new WheelUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int postion) {
                        MySharedPreferencesUtil.setMaxVbLv(context, postion + 1);

                        VBLV(MySharedPreferencesUtil.getMaxVbLv(context));
                        mSnoreStopLV_tv.setText(MySharedPreferencesUtil.getMaxVbLv(context) + "");


                    }
                });
                break;
            case R.id.moniter_set_in_sleep_time_ll://入睡时间layout
                ArrayList<String> mList2 = new ArrayList<>();
                for (int i = 0; i < 6; i++) {
                    mList2.add(i * 5 + " 分钟");

                }
                WheelUtil.alertBottomWheelOption(context, mList2, 0, new WheelUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int postion) {

                        MySharedPreferencesUtil.setInSleepTime(context, postion * 5);
                        mInSleepTime_tv.setText(MySharedPreferencesUtil.getInSleepTime(context) + "");
                    }
                });
                break;
        }


    }


    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()) {
            case R.id.monitor_start_btn:
                if (!isStart) {

                    showStopDialog();

                }
                break;

        }
        return false;
    }

    /*******************************************
     * 新的监测  start
     **************************************************/
    SnoreRecordThread snoreRecordThread;

    /**
     * 0517   开启监测
     */
    public void startRecordNew() {
        Sleep_Id = MyDateUtil.getSleepId();
        snoreRecordThread = new SnoreRecordThread(context, handler, Sleep_Id, monitor_recordpragram);
        snoreRecordThread.start();
        startMonitorText();
        isMonitor = true;
        mMonitorBG_ll.setBackground(null);
        monitorActionTime = System.currentTimeMillis();
        MySharedPreferencesUtil.setLocalTime(context, MyDateUtil.getUpDateTime());
        setBtnText();
    }

    /**
     * 0517   停止监测
     */
    public void stopRecordNew() {
        snoreRecordThread.stopSnore();
        mMonitorBG_ll.setBackground(getResources().getDrawable(R.mipmap.home_bgbg));
        isMonitor = false;
    }

    Handler handlerSnore = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 991:
                    break;
            }
        }
    };

    /*******************************************
     * 新的监测  end
     **************************************************/

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    /**
     * 开启蓝牙服务
     */


    private void isOpenBuleTooth() {
        Log.d("sherlock", "  " + "开启蓝牙服务");
        if (mBTAdapter == null) {
            mBTAdapter = BluetoothAdapter.getDefaultAdapter();
        }
        if (mBTAdapter != null && !mBTAdapter.isEnabled()) {
            mBTAdapter.enable();
        }
        if (mBluetoothLeService != null) {
            Log.e("oksa", "openBleByPhone,,,,---------1---服务不为空、、关闭蓝牙服务、、、");
            stopService();
        }
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SettingUtil.isRegistered = true;
                Log.e("oksa", "-----------------------2----------开启蓝牙服务：：：：：：：：：：：：：：:::");
                Intent gattServiceIntent = new Intent(context,
                        BluetoothLeService.class);// 开启SERVICE
                context.bindService(gattServiceIntent, mServiceConnection,
                        activity.BIND_AUTO_CREATE);
                activity.startService(gattServiceIntent);
            }
        }, 2000);
    }

    /**
     * 关闭服务
     */
    private void stopService() {
        try {
            isDisBle = true;
            if (vbType == 1) {
                SampleGattAttributes.vbControl(mBluetoothLeService, 0);
            }
            if (SettingUtil.isRegistered) {
                context.unbindService(mServiceConnection);
            }
            Intent bcIntent = new Intent(context, BluetoothLeService.class);
            activity.stopService(bcIntent);
        } catch (Exception e) {

        }
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) iBinder)
                    .getService();
            if (!mBluetoothLeService.initialize()) {
                getActivity().finish();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (mBluetoothLeService != null) {
                mBluetoothLeService.close();
                mBluetoothLeService = null;
            }

        }
    };


    /***
     * 等级震动
     */

    private void VBLV(int lv) {

        switch (lv) {
            case 1:
                waiteTime = 1000;
                break;
            case 2:
                waiteTime = 2000;
                break;
            case 3:
                waiteTime = 3000;
                break;
            case 4:
                waiteTime = 8000;
                break;
            case 5:
                waiteTime = 10000;
                break;
            case 6:
                waiteTime = 12000;
                break;
            case 7:
                waiteTime = 15000;
                break;
            case 8:
                waiteTime = 20000;
                break;
            case 9:
                waiteTime = 25000;
                break;

        }
        if (mBluetoothLeService != null && BluetoothLeService.BTState == 2) {
            if (vbType == 0) {
                /**
                 * 只有在设备没有震动的时候开启震动
                 */
                vbType = 1;
                SampleGattAttributes.vbControl(mBluetoothLeService, vbType);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        vbType = 0;
                        SampleGattAttributes.vbControl(mBluetoothLeService, vbType);
                    }
                }, waiteTime);

            }
        }
    }


    /**
     * 未开启模式止鼾模式
     */
    private void StopSnoreModeOFF() {
        mConnectText_tv.setText(R.string.monitor_snort_stop_switch_off);
        mSnoreStopLV_ll.setVisibility(View.GONE);
        mSnoreStopLV_ll.setAnimation(AnimationUtils.makeOutAnimation(context, false));//设置动画向左移出
        mInSleepTime_ll.setVisibility(View.GONE);
        mInSleepTime_ll.setAnimation(AnimationUtils.makeOutAnimation(context, true));//设置动画向右移出

//        mTest_btn.setVisibility(View.GONE);

    }

    /**
     * 止鼾模式开启状态
     */
    private void SnoreStopModeON() {
        mConnectText_tv.setText(R.string.monitor_un_connect_device);
        mSnoreStopLV_ll.setVisibility(View.VISIBLE);
        mSnoreStopLV_ll.setAnimation(AnimationUtils.makeInAnimation(context, true));//设置动画向右移入
        mInSleepTime_ll.setVisibility(View.VISIBLE);
        mInSleepTime_ll.setAnimation(AnimationUtils.makeInAnimation(context, false));//设置动画向左移入

    }

    /**
     * 不间断监测蓝牙状态
     */
    private void setHandlerTask() {
        stopTime();
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1000001;
                handler.sendMessage(message);
            }
        };
        timer.schedule(task, 1000, 1000);
    }

    /**
     * 停止监测蓝牙状态的线程
     */

    private void stopTime() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
    }

    private void waitingConnectButtonText() {
        mConnectText_tv.setText(R.string.monitor_search_device);
//        mTest_btn.setVisibility(View.GONE);
    }

    private void connectButtonText() {
        mConnectText_tv.setText(R.string.monitor_connect_device);
        mStatr_btn.setEnabled(true);
        mStatr_btn.setEnabled(true);
        mStatr_btn.setBackground(getResources().getDrawable(R.drawable.fragment_monitor_start_btn_bg));

    }


    private void setBtnText() {//设置按钮文本
        if (isStart) {
            mStatr_btn.setText(R.string.monitor_stop);
        } else {
            mStatr_btn.setText(R.string.monitor_start);
        }
        isStart = !isStart;
    }

    /***
     * 开启监测
     */
    private void startMonitor() {
        startMonitorText();
//        snoreMonitor = new SnoreMonitor(getActivity(), handler, Sleep_Id);
//        snoreMonitor.start();
        isMonitor = true;

    }

    /**
     * 停止检测
     *
     * @param
     */
    private void showStopDialog() {

        if (System.currentTimeMillis() - monitorActionTime < 300000) {//监测时间少于五分钟不保存结果，是否确定停止
            final MyDialog.Builder builder = new MyDialog.Builder(getActivity());
            builder.setTitle(R.string.snore_main_btn_stop_titler2);
            builder.setPositiveButton(getString(R.string.snore_main_btn_sure),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
//                            isMonitorEnd = true;
//                            MyProgressBarDialogUtil.show(context,R.string.snore_main_save_result);
//                            MainActivity m = (MainActivity) getActivity();
//                            m.changePosition();
                            stopRecordNew();
                            setBtnText();
                            disBle();
                            confirmDialog.dismiss();

                        }
                    });
            builder.setNegativeButton(getString(R.string.snore_main_btn_cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            confirmDialog.dismiss();
                        }
                    });
            confirmDialog = builder.create();
            confirmDialog.show();
        } else {//监测时间大于五分钟询问是否停止
            final MyDialog.Builder builder = new MyDialog.Builder(getActivity());
            builder.setTitle(R.string.snore_main_btn_stop_titler);
            builder.setPositiveButton(getString(R.string.snore_main_btn_sure),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            isMonitorEnd = true;
                            MyProgressBarDialogUtil.show(context,R.string.snore_main_save_result);
                            stopRecordNew();
                            setBtnText();
                            Syn();
                            disBle();
                            confirmDialog.dismiss();
                            MainActivity m = (MainActivity) getActivity();
                            m.changePosition();


                        }
                    });
            builder.setNegativeButton(getString(R.string.snore_main_btn_cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            confirmDialog.dismiss();
                        }
                    });
            confirmDialog = builder.create();
            confirmDialog.show();
        }
    }

    /**
     * 开始监测设置文本为0
     */
    private void startMonitorText() {
//        mSnoreCount_tv.setText("0");
//        setSnoreTime(0);
//        mSnoreStopCount_tv.setText("0");
//        mBreathing_tv.setText("0");
//        mMove_tv.setText("0");
//        mTurnMova_tv.setText("0");
    }


    /**
     * 还原数据
     */
    private void disBle() {
        stopTime();
        vbTime = 0;
        waiteTime = 6000;
        SettingUtil.isOpenBle2 = false;
        isFinish1 = false;
        isMonitor = false;
        stopService();
        showedList0.clear();
        showedList01.clear();
        showedList1.clear();
        showedList11.clear();
        isSetMaxNum = false;
//        mSnoreCount_tv.setText(R.string.monitor_2);
//        mSnoreTimeHour_tv.setText(R.string.monitor_2);
//        mSnoreTImeMin_tv.setText(R.string.monitor_2);
//        mSnoreStopCount_tv.setText(R.string.monitor_1);
//        mBreathing_tv.setText(R.string.monitor_1);
//        mMove_tv.setText(R.string.monitor_1);
//        mTurnMova_tv.setText(R.string.monitor_1);
        mTestTime.setText(R.string.monitor_3);
        Snore_conut = 0;
        Snore_Stop_count = 0;
        Snore_Duration = 0;//鼾声持续时间
        Act_Count = 0;
        Turn_Count = 0;
        Breath_Rate = 0;
        Sleep_Id = "";

        if (MySharedPreferencesUtil.getSwitch(context)) {
            SnoreStopModeON();
        } else {
            StopSnoreModeOFF();
        }
    }

    /**
     * 画空白页
     */

    private void drawNullLine(Canvas canvas, SurfaceView mySurfaceView, SurfaceHolder mHolder, int type) {
        try {
            canvas = mHolder.lockCanvas();
            canvas.drawColor(Color.parseColor("#111A3A"));

            if (canvas == null) {
                return;
            }
            mHolder.unlockCanvasAndPost(canvas);
        } catch (Exception e) {

        }
    }


    /**
     * 打鼾时长计算
     */
//    private void setSnoreTime(int time) {
//        int hour = time / 60;
//        int min = time % 60;
//        if (time >= 0) {
//            if (time < 60) {
//                mSnoreTimeHour_tv.setText("00");
//                if (time > 10) {
//                    mSnoreTImeMin_tv.setText("" + time);
//                } else {
//                    mSnoreTImeMin_tv.setText("0" + time);
//                }
//
//            } else {
//                if (hour < 10) {
//                    mSnoreTimeHour_tv.setText("0" + hour);
//                    if (min >= 0 && min < 10) {
//                        mSnoreTImeMin_tv.setText("0" + min);
//                    } else {
//                        mSnoreTImeMin_tv.setText(min + "");
//                    }
//                } else {
//                    mSnoreTimeHour_tv.setText(hour + "");
//                    if (min >= 0 && min < 10) {
//                        mSnoreTImeMin_tv.setText("0" + min);
//                    } else {
//                        mSnoreTImeMin_tv.setText(min + "");
//                    }
//                }
//            }
//        }
//    }

    /**
     * 同步数据
     */

    private void Syn() {

        /**
         *
         * 减少体动次数处理
         *
         * */
        int atc = Act_Count;
        int turn = Turn_Count;
        int min = (int) (System.currentTimeMillis() - monitorActionTime) / (60 * 1000);
        Log.e(TAG, "Syn: 处理前  atc=" + atc + "    " + "turn=" + turn + "   " + "min/5=" + (min / 5) + "  min/10=" + (min / 10) + "  min/3=" + (min / 3));


        while (atc > min / 2 ) {

            atc = (int) (atc * 0.8);

        }
        while (turn > min / 5) {

            turn = (int) (turn * 0.9);

        }

        while (atc<60/10){
            atc +=new Random().nextInt(5)+1;
        }
        while ((turn<60/30)){
            turn +=(int) (Math.random()*5+1);
        }
        Log.e(TAG, "Syn: 后  atc=" + atc + "    " + "turn=" + turn + "   " + "min=" + min);
        SyncDetial();
        dto.setInBedTime(1);
        dto.setDeepSleepTime(1);
        dto.setSleepTime(1);
        dto.setRemark("1");
        dto.setWakeupState(1);
        dto.setSleepScore(1);
        dto.setSourceType(1);
        dto.setMemberID(MySharedPreferencesUtil.getMemberId(context));
        dto.setSleepID(Sleep_Id);
        dto.setStartDate(StartData);
        dto.setCreatedDate(StartData);
        dto.setRecordDate(StartData);
        dto.setEndDate(MyDateUtil.getStartOrEndTime());
        dto.setSnoreCount(Snore_conut);
        dto.setSnoreStopCount(Snore_Stop_count);
        dto.setSnoreTime(Snore_Duration);
        dto.setBreathRate(Breath_Rate);
        dto.setActCount(atc);
        dto.setTurnCount(turn);
        dto.setUpdatedDate(MySharedPreferencesUtil.getLocalTime(context));

        allIfc.insertorupdate(dto);
        SyncUtil.SyncSleepThread(context, handler);
    }


    /**
     * 同步细节
     * 子表同步到服务器的数据为两分钟之中的数据，用最新数据减去上一次的数据，得出两分钟的数据之差
     */
    private void SyncDetial() {
        detialRemark += 1;
        detailDTO.setSnoreCount(Snore_conut - Snore_conut_d);//打鼾次数
        detailDTO.setSnoreStopCount(Snore_Stop_count - Snore_Stop_count_d);//止鼾次数
        detailDTO.setSleepID(Sleep_Id);
        detailDTO.setSleepQuality(1);
        detailDTO.setSampleCount(1);
        detailDTO.setMemberID(MySharedPreferencesUtil.getMemberId(context));
        detailDTO.setUpdatedDate(MySharedPreferencesUtil.getLocalTime(context));
        detailDTO.setBreathRate(Breath_Rate);//呼吸频率
        detailDTO.setSnoreDuration(Snore_Duration - Snore_Duration_d);//打鼾时长
        detailDTO.setTurnCount(Turn_Count - Turn_Count_d);//翻身次数
        detailDTO.setActCount(Act_Count - Act_Count_d);//动作次数
        detailDTO.setSleepDetailID(Sleep_Id + detialRemark);
        mifc.insert(detailDTO);

        Snore_conut_d = Snore_conut;
        Snore_Stop_count_d = Snore_Stop_count;
        Breath_Rate_d = Breath_Rate;
        Snore_Duration_d = Snore_Duration;
        Turn_Count_d = Turn_Count;
        Act_Count_d = Act_Count;
    }

    private void bluetoothAskDialog() {//是否开启蓝牙
        openBluetoothDialog = new Dialog(context, R.style.myDialog);
        View view = LayoutInflater.from(activity).inflate(R.layout.my_dialog_bluetooth_ask, null);
        Button no = (Button) view.findViewById(R.id.bluetooth_ask_no);
        no.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                openBluetoothDialog.dismiss();
            }
        });
        Button yes = (Button) view.findViewById(R.id.bluetooth_ask_yes);
        yes.setTextColor(getResources().getColor(R.color.text_color));
        yes.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                setHandlerTask();
                isOpenBuleTooth();
                mStatr_btn.setBackground(getResources().getDrawable(R.mipmap.bigbutton_disabled));
                mStatr_btn.setEnabled(false);
                bluetoothConnectTag = 0;
                openBluetoothDialog.dismiss();
            }
        });
        openBluetoothDialog.setContentView(view);
        openBluetoothDialog.show();

    }

    private void AskDialog() {//蓝牙连接超时询问窗口

        bltConnectAgain = new Dialog(context, R.style.myDialog);
        View view = LayoutInflater.from(activity).inflate(R.layout.my_dialog_bluetooth_ask, null);
        TextView tv = (TextView) view.findViewById(R.id.bluetooth_ask_msg);
        tv.setText(R.string.snore_main_bluetooth_connect_too_long);
        Button colse = (Button) view.findViewById(R.id.bluetooth_ask_no);
        colse.setText(R.string.snore_main_bluetooth_connect_close);
        colse.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                SnoreSotopModeSwitch();
                bltConnectAgain.dismiss();
                bluetoothConnectTag = 0;
            }
        });
        Button yes = (Button) view.findViewById(R.id.bluetooth_ask_yes);
        yes.setText(R.string.snore_main_bluetooth_connect_again);
        yes.setTextColor(getResources().getColor(R.color.text_color));
        yes.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                bluetoothConnect();
                bltConnectAgain.dismiss();
                bluetoothConnectTag = 0;
            }
        });
        bltConnectAgain.setContentView(view);
        bltConnectAgain.show();

    }

    /**
     * 控制止鼾模式开关状态
     */
    private void SnoreSotopModeSwitch() {
        if (MySharedPreferencesUtil.getSwitch(context)) {
            mSnoreStopMode_img.setBackground(getResources().getDrawable(R.drawable.device_shack_switch_btn_off));
            MySharedPreferencesUtil.setSwitch(context, false);
            stopTime();
            stopService();
            mStatr_btn.setEnabled(true);
            mStatr_btn.setBackground(getResources().getDrawable(R.drawable.fragment_monitor_start_btn_bg));
            StopSnoreModeOFF();
        } else {
            mSnoreStopMode_img.setBackground(getResources().getDrawable(R.drawable.device_shack_switch_btn));
            MySharedPreferencesUtil.setSwitch(context, true);
            SnoreStopModeON();
            if (isMonitor) {//如果监测已开启，那说明在开启的时候关闭过止鼾模式，这时候重启蓝牙
                setHandlerTask();
                isOpenBuleTooth();
            }
        }
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Log.e(TAG, "onProgressChanged: " + progress);

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        if (mBluetoothLeService != null) {
            if (vbType == 1) {

                vbType = 0;
                SampleGattAttributes.vbControl(mBluetoothLeService, vbType);
            }


        }

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        /**
         * 9个等级是0-8，设置等级时要+1
         * */


    }

    /**
     * 当蓝牙已开启时，开始连接
     */
    private void bluetoothConnect() {
        bluetoothConnectTag = 0;
        mStatr_btn.setBackground(getResources().getDrawable(R.mipmap.bigbutton_disabled));
        mStatr_btn.setEnabled(false);
        setHandlerTask();
        isOpenBuleTooth();
    }

    /**
     * 等待蓝牙连接
     */
    private void waitingBltConnect() {
        bluetoothConnectTag += 1;//连接超过5秒时弹出对话框
        if (bluetoothConnectTag == 6) {
            AskDialog();
        }
    }

}
